/**
 * @name: 钱保留两位小数 不足补0
 * @param {String | Number} value 要处理的数据
 * @param {Number} tofixed 保留几位小数
 * @return {*}
 */
export const toDecimal = (value) => {
  const num = parseFloat(value);
  if (isNaN(num)) return;
  let rn = (parseInt(num * 100) / 100).toString();
  let rs = rn.indexOf('.');
  if (rs < 0) {
    rs = rn.length;
    rn += '.';
  }
  while (rn.length <= rs + 2) {
    rn += '0';
  }
  return rn;
};

/**
 * @name: 获取地址栏参数
 * @param {string} name 需要获取的参数
 * @return {*}
 */
export const GetQueryString = (name) => {
  let reg = new RegExp(`(^|&)${name}=([^&]*)(&|$)`, 'i');
  let r = location.search.substr(1).match(reg);
  if (r != null) return unescape(decodeURI(r[2]));
  return null;
};

/**
 * @name: 根据身份证号提取年龄
 * @param {String} iden身份证号
 * @return {*}
 */
export const getAge = (iden) => {
  let val = iden.length;
  let myDate = new Date();
  let month = myDate.getMonth() + 1;
  let day = myDate.getDate();
  let age = 0;
  if (val === 18) {
    age = myDate.getFullYear() - iden.substring(6, 10) - 1;
    if (
      iden.substring(10, 12) < month ||
      (iden.substring(10, 12) == month && iden.substring(12, 14) <= day)
    ) {
      age++;
    }
  }
  return age;
};

/**
 * @name: 日期格式化
 * @param {Date} objDate 'new Date()'
 * @param {string} fmt 'yyyy-MM-dd HH:mm:ss'(传入的格式)
 * @return {*}
 */
export const formatDate = (objDate, fmt) => {
  const o = {
    'M+': objDate.getMonth() + 1, // 月份
    'd+': objDate.getDate(), // 日
    'h+': objDate.getHours() % 12 === 0 ? 12 : objDate.getHours() % 12, // 小时
    'H+': objDate.getHours(), // 小时
    'm+': objDate.getMinutes(), // 分
    's+': objDate.getSeconds(), // 秒
    'q+': Math.floor((objDate.getMonth() + 3) / 3), // 季度
    S: objDate.getMilliseconds() // 毫秒
  };
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(
      RegExp.$1,
      `${objDate.getFullYear()}`.substr(4 - RegExp.$1.length)
    );
  }
  Object.keys(o).forEach((k) => {
    if (new RegExp(`(${k})`).test(fmt)) {
      fmt = fmt.replace(
        RegExp.$1,
        RegExp.$1.length === 1 ? o[k] : `00${o[k]}`.substr(`${o[k]}`.length)
      );
    }
  });
  return fmt;
};

export const formatDateStamp = (dateTime) => {
  let date = new Date(dateTime);
  let YY = date.getFullYear() + '-';
  let MM =
    (date.getMonth() + 1 < 10
      ? '0' + (date.getMonth() + 1)
      : date.getMonth() + 1) + '-';
  let DD = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
  return YY + MM + DD;
};

export const getQueryVariable = (variable) => {
  var query = window.location.search.substring(1);
  var vars = query.split('&');
  for (var i = 0; i < vars.length; i++) {
    var pair = vars[i].split('=');
    if (pair[0] == variable) {
      return pair[1];
    }
  }
  return false;
};

function filter(str) {
  // 特殊字符转义
  str += ''; // 隐式转换
  str = str.replace(/%/g, '%25');
  str = str.replace(/\+/g, '%2B');
  str = str.replace(/ /g, '%20');
  str = str.replace(/\//g, '%2F');
  str = str.replace(/\?/g, '%3F');
  str = str.replace(/&/g, '%26');
  str = str.replace(/\\=/g, '%3D');
  str = str.replace(/#/g, '%23');
  return str;
}
export const formateObjToParamStr = (paramObj) => {
  const sdata = [];
  // console.log(paramObj);
  for (let attr in paramObj) {
    if (
      !paramObj[attr] &&
      typeof paramObj[attr] != 'undefined' &&
      paramObj[attr] != 0
    ) {
      console.log(attr);
      delete paramObj.attr;
    } else {
      sdata.push(`${attr}=${filter(paramObj[attr])}`);
    }
    console.log(paramObj);
  }
  return sdata.join('&');
};

export const url2json = () => {
  let search = window.location.search;
  if (search) {
    if (search.indexOf('?') == 0) {
      search = search.substring(1);
    }
    return JSON.parse(
      '{"' + search.replace(/&/g, '","').replace(/=/g, '":"') + '"}',
      (key, value) => {
        return key === '' ? value : decodeURIComponent(value);
      }
    );
  }
  return {};
};

/**
 * @name: 下载文件
 * @param {*} href
 * @param {*} name
 * @return {*}
 */
export const DownloadFile = (href, name) => {
  const a = document.createElement('a');
  const e = document.createEvent('MouseEvents'); // 创建鼠标事件对象
  e.initEvent('click', false, false); // 初始化事件对象
  a.href = href; // 设置下载地址
  a.target = '_blank'; // 打开新窗口
  a.download = name; // 设置下载文件名
  a.dispatchEvent(e); // 给指定的元素，执行事件click事件
};
